<?php
/**
 * Jobs Model for Jobs World Component
 * 
 * @package    Joomla.Tutorials
 * @subpackage Components
 * @link http://docs.joomla.org/Developing_a_Model-View-Controller_Component_-_Part_2
 * @license    GNU/GPL
 */
 
// No direct access
 
defined( '_JEXEC' ) or die( 'Restricted access' );
 
jimport( 'joomla.application.component.model' );
 
/**
 * Jobs Model
 *
 * @package    Joomla.Tutorials
 * @subpackage Components
 */
class JobsModelMyJobs extends JModel
{
	/**
	 * Category ata array
	 *
	 * @var array
	 */
	var $_data = null;

	/**
	 * Category total
	 *
	 * @var integer
	 */
	var $_total = null;

	/**
	 * Pagination object
	 *
	 * @var object
	 */
	var $_pagination = null;

	/**
	 * Constructor
	 *
	 * @since 1.5
	 */
	function __construct()
	{
		parent::__construct();

		global $mainframe, $option;
	}
	

	function saveEmailNewsletter($name,$email, $firma_navn=''){
		$db =& JFactory::getDBO();		
		$query = 'SELECT count(*) as "total" FROM #__jnews_subscribers where email = "'.$email.'"';
	    $db->setQuery( $query );
	    $row = $db->loadObject();
		if($row->total > 0) {
			echo 0;
			return false;
		}
		
		 
		$query = "INSERT INTO `#__jnews_subscribers`(`user_id` ,`name` ,`email` ,`receive_html` ,`confirmed` ,`blacklist` ,`timezone` ,`language_iso` ,`ip` ,`subscribe_date`) VALUES ('0', '".$name."', '".$email."', '1', '1', '0', '00:00:00', 'eng', NULL , '0')";
		
		$db->setQuery( $query );							
		if($db->query())
		{
			$idinsert = $db->insertid();
			$query = "INSERT INTO `#__jnews_listssubscribers` (`list_id`, `subscriber_id`, `subdate`, `unsubdate`, `unsubscribe`) VALUES ('1','".$idinsert."', ".time().", '0', '0')";
			//echo $query;
			$db->setQuery( $query );
			$db->query();
			echo 1;
			$this->sentNewsletterSuccess($email,$firma_navn);
			return true;
		}
		echo 0;
		return false;
	}
	
	public function sentNewsletterSuccess($email,$firma_navn)
		{
			
			$html= "<br/>Hej:".$firma_navn;
			$html.= "<br/>Denne e-mail-adresse er nu tilmeldt vores nyhedsbrev.";
			
			$html.= "<br/><br/>Med venlig hilsen,
					<br/><a href='http://www.3malertilbud.dk'><b>3malertilbud.dk</b></a
					<br/><a href='mailto:info@3malertilbud.dk'>info@3malertilbud.dk</a>";
			$html.= "<br/><img src='".JURI::root()."/templates/3dmaler/img/email_logo_footer.jpg'></img>";	
				
			$app		= JFactory::getApplication();	
			$mailfrom	= $app->getCfg('mailfrom');
			$fromname	= $app->getCfg('fromname');
			$sitename	= $app->getCfg('sitename');
			$name		= '';
			$email		= $email;
			
			$subject	= 'Tilmeld Nyhedsbrev';
			$body		= $html;
			
			// Prepare email body
			//JURI::base();
			$body	= stripslashes($body);
			$mail = JFactory::getMailer();
			//echo $mailfrom;
			
			//echo $html;
			//exit();
			$mail->sendMail($mailfrom, $fromname, $email, $subject, $body, $mailfrom);	
			
		} 
		
	function removeNewsletter($email){
		$db =& JFactory::getDBO();
		$query = 'SELECT * FROM #__jnews_subscribers where email = "'.$email.'"';
	    $db->setQuery( $query );
	    $row = $db->loadObject();
		
		if(isset($row)) {		 
			//$query = "UPDATE `#__jnews_subscribers` SET confirmed=0 WHERE email='".$email."'";
			$query = "DELETE FROM `#__jnews_listssubscribers` WHERE list_id='".$row->id."'";
			$db->setQuery( $query );
			$db->query();
			
			$query = "DELETE FROM `#__jnews_subscribers` WHERE id='".$row->id."'";
			$db->setQuery( $query );
			$db->query();
			echo 1;
			return true;
		} else {
			echo 0;
			return false;
		}
	}
	function getDetailJob($id)
    {
		$db =& JFactory::getDBO();
	    $query = 'SELECT * FROM #__jobs where id = '.$id;
	    $db->setQuery( $query );
	    $row = $db->loadObject();
        return $row;
    }	
	function getPrisJob($catid)
    {
		$db =& JFactory::getDBO();
	    $query = 'SELECT * FROM #__categories where id = '.$catid;
	    $db->setQuery( $query );
	    $row = $db->loadObject();
        return $row;
    }
	
	function getNameCityDanish($id)
    {
		$city = $this->getArrayCityDanish();
		for($i=0;$i<sizeof($city);$i++)
		{
			if($id>=$city[$i]['from'] && $id<=$city[$i]['to']) {
				return $city[$i]['name'];
			}
		}
        return 'Indtast din postnr';
    }
	
	function getArrayCityDanish()
    {
		$city = array();
		$city[0] = array("from"=>0,"to"=>0,"name"=>"Hele Danmark");
		$city[1] = array("from"=>1000,"to"=>2999,"name"=>"København og omegn");
		$city[2] = array("from"=>3000,"to"=>3699,"name"=>"Nordsjælland");
		$city[3] = array("from"=>3700,"to"=>3799,"name"=>"Bornholm");
		//$city[4] = array("from"=>4000,"to"=>4999,"name"=>"Resten af Sjælland, Lolland-Falster og Møn");
		$city[4] = array("from"=>4000,"to"=>4999,"name"=>"Resten af Sjælland");
		$city[5] = array("from"=>5000,"to"=>5999,"name"=>"Fyn og øer ");
		$city[6] = array("from"=>6000,"to"=>6999,"name"=>"Syd-og Sønderjylland ");
		$city[7] = array("from"=>7000,"to"=>7999,"name"=>"Midt-og Vestjylland");
		$city[8] = array("from"=>8000,"to"=>8999,"name"=>"Østjylland");
		$city[9] = array("from"=>9000,"to"=>9999,"name"=>"Nordjylland");
		
		/*
		$city[0] = array("from"=>1000,"to"=>2999,"name"=>"København og omegn");
		$city[1] = array("from"=>3000,"to"=>3699,"name"=>"Nordsjælland");
		$city[2] = array("from"=>3700,"to"=>3799,"name"=>"Bornholm");
		$city[3] = array("from"=>4000,"to"=>4999,"name"=>"Resten af Sjælland, Lolland-Falster og Møn ");
		$city[4] = array("from"=>5000,"to"=>5999,"name"=>"Fyn og øer ");
		$city[5] = array("from"=>6000,"to"=>6999,"name"=>"Syd-og Sønderjylland ");
		$city[6] = array("from"=>7000,"to"=>7999,"name"=>"Midt-og Vestjylland");
		$city[7] = array("from"=>8000,"to"=>8999,"name"=>"Østjylland");
		$city[8] = array("from"=>9000,"to"=>9999,"name"=>"Nordjylland");
		*/
        return $city;
    }

	function getListImageJobs($id)
    {
		$db =& JFactory::getDBO();
	    $query = 'SELECT * FROM #__jobs_images where jobs_id = '.$id;
	    $db->setQuery( $query );
	    $rows = $db->loadObjectList();
        return $rows;
    }
	function getActorDetail($id)
    {
		$db =& JFactory::getDBO();
	    $query = 'SELECT * FROM #__jobs where id = '.$id;
	    $db->setQuery( $query );
	    $row = $db->loadObject();
        return $row;
    }
	function getSortJobs()
    {		
      $jsort = array();
	  $jsort[] = array("value"=>"1","name"=>"Oprettelsesdato");
	  //$jsort[] = array("value"=>"2","name"=>"Ønsket slutdato");
	  $jsort[] = array("value"=>"3","name"=>"Estimeret pris");
	  $jsort[] = array("value"=>"4","name"=>"Landsdel");
	  return $jsort;
    }
	function getSortMyJobs()
    {		
      $jsort = array();
	  $jsort[] = array("value"=>"1","name"=>"Oprettelsesdato");
	  //$jsort[] = array("value"=>"2","name"=>"Ønsket slutdato");
	  $jsort[] = array("value"=>"3","name"=>"Estimeret pris");
	  $jsort[] = array("value"=>"4","name"=>"Landsdel");
	  $jsort[] = array("value"=>"5","name"=>"Status");
	  return $jsort;
    }
	function getListPris()
    {
		$db =& JFactory::getDBO();
	    $query = "SELECT * FROM #__categories where extension = 'com_jobs' and published=1 order by id ASC";
	    $db->setQuery( $query );
	    $row = $db->loadObjectList();
        return $row;
    }
	function getUserWorkInfo($userid,$jobid)
    {
		$db =& JFactory::getDBO();
	    $query = "SELECT * FROM #__uworks where state !=-2 AND userid=".$userid." AND jobid=".$jobid;
	    $db->setQuery( $query );
	    $row = $db->loadObject();
		
		return $row;
	}
	function getListWorks($sid=0,$name='works',$disable=0)
    {
		$db =& JFactory::getDBO();
	    $query = "SELECT * FROM #__categories where extension = 'com_uworks' and published = 1 order by id ASC";
	    $db->setQuery( $query );
	    $wlist = $db->loadObjectList();
		if($disable==1) {
			$html = '<select id="'.$name.'" name="'.$name.'" disabled="disabled" class="option2">';
		} else {
			$html = '<select id="'.$name.'" name="'.$name.'" class="option2">';
		
		}
		/*if($sid == 43 ) { $html = '<select id="works_2" style="color:#F00;" name="works_2" class="udfort" disabled="disabled">';} 
		if($sid == 44 ) { $html = '<select id="works_2" style="color:#F00;" name="works_2" class="afslaet" disabled="disabled">';} 
		*/
		for($i=0;$i<sizeof($wlist);$i++) 
		{
			if($sid==$wlist[$i]->id)
			 $html .= '<option selected="selected" value="'.$wlist[$i]->id.'">'.$wlist[$i]->title.'</option>';
		    else
		     $html .= '<option value="'.$wlist[$i]->id.'">'.$wlist[$i]->title.'</option>';
		    	 
		}
		$html .= '</select>';
		
		
        return $html;
    }
	
	function getCategoriesName($id)
    {
		$db =& JFactory::getDBO();
	    $query = "SELECT * FROM #__categories where id = ".$id;
	    $db->setQuery( $query );
	    $row = $db->loadObject();
		return $row;
	}
		
	
	public function trunchtml($text = "", $chars=150, $ending='', $exact='no', $inline='', $threshold='') {

    $raw = strlen(preg_replace('/<.*?>
/', '', $text));         
          if ( $raw <= $chars) {
              $return_data = $text;
              return $return_data;
          }
                    if ( $threshold > 0 && $raw < $threshold )
                    {
                        $return_data = $text;
                        return $return_data ;
                    }
          preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
          $total_length = 0;
          $open_tags = array();
          $truncate = '';
          foreach ($lines as $line_matchings) {
              if (!empty($line_matchings[1])) {
                  if (preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $line_matchings[1])) 
                  {
                  } 
                  elseif (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $line_matchings[1], $tag_matchings)) 
                  {
                      $pos = array_search($tag_matchings[1], $open_tags);
                      if ($pos !== false) 
                      {
                          unset($open_tags[$pos]);
                      }
                  } 
                  elseif (preg_match('/^<\s*([^\s>!]+).*?>$/s', $line_matchings[1], $tag_matchings)) 
                  {
                      array_unshift($open_tags, strtolower($tag_matchings[1]));
                  }
                  $truncate .= $line_matchings[1];
              }
              $content_length = strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $line_matchings[2]));

              if ($total_length + $content_length > $chars) 
              {
                  $left = $chars - $total_length;
                  $entities_length = 0;
                  if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', $line_matchings[2], $entities, PREG_OFFSET_CAPTURE|PREG_PATTERN_ORDER)) 
                  {
                      foreach ($entities[0] as $entity) 
                      {
                          if ($entity[1] + 1 - $entities_length <= $left) 
                          {
                              $left--;
                              $entities_length += strlen($entity[0]);
                          } 
                          else 
                          {
                              break;
                          }
                      }
                  }
                  $truncate .= substr($line_matchings[2], 0, $left + $entities_length);
                  break;
              } 
              else 
              {
                  $truncate .= $line_matchings[2];
                  $total_length += $content_length;
              }
              if ($total_length >= $chars) {
                  break;
              }
          }
          if ($exact != "yes") {
                            $last_gt = strrpos($truncate, '>');
                            $spacepos = strrpos($truncate, ' ');
                            if ( ($last_gt !== FALSE && $spacepos !== FALSE) && $last_gt > $spacepos ) 
                            {
                                $spacepos = strrpos($truncate, '<');
                                if ($spacepos !== FALSE)
                                {
                                    $truncate = substr($truncate, 0, $spacepos);
                                    array_shift($open_tags);
                                }
                            }
                            elseif ( $spacepos !== FALSE ) 
              {
                  $truncate = substr($truncate, 0, $spacepos);
              }
          }
          $truncate = rtrim($truncate);
          if (!empty($inline)) {
                if (substr($inline,0,1)=="_") {
                    $inline = " ".ltrim($inline,"_");
                }
              $truncate .= $inline;
          }
          foreach ($open_tags as $tag) {
              $truncate .= '</' . $tag . '>';
          }
          if ( !empty($ending) ) {
              $truncate .= $ending;
          }
          return $truncate;

      }
}